package com.squirrel.common.config;

import com.squirrel.common.interceptor.JwtInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Web配置类
 *
 * @author olay
 * @version 1.0
 * @date 6/2/2021 1:39 PM
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 优先加载
     * @author 关远键
     * @date 2021/11/27 22:15
     * @return com.squirrel.common.interceptor.JwtInterceptor
     */
    @Bean
    public JwtInterceptor jwtInterceptor() {
        return new JwtInterceptor();
    }

    /**
     * 解决返回中文乱码
     *
     * @return
     */
    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        return new StringHttpMessageConverter(Charset.forName("UTF-8"));
    }

    /**
     * 解决返回中文乱码
     *
     * @return
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        WebMvcConfigurer.super.configureMessageConverters(converters);
        converters.add(responseBodyConverter());
    }


    /**
     * 添加Web项目的拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 对所有访问路径（除了 swagger 访问路径），都通过 JwtInterceptor 类型的拦截器进行拦截
        registry.addInterceptor(jwtInterceptor())
                .addPathPatterns("/api/**")
                .excludePathPatterns("/swagger-resources/**",
                        "/webjars/**",
                        "/v2/**",
                        "/swagger-ui/**",
                        "/druid/**",
                        "/csrf");
    }
}
